package game.ui;

import game.GameConfiguration;
import game.connection.GameClient;
import game.connection.GameServer;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;

/**
 * This is the Main class of this game.
 * It is the GUI for user to create server or client.
 * This 
 * 
 * @author Sarun Wongtanakarn 5510546166
 * @author Apiwat Jierakulpanit 5510546212
 * @Version 2013.05.01
 */
public class GameCreatorUI extends JFrame {
	private JTextField showIPTextField;
	private JTextField serverSelectPortTextField;
	private JTextField setNameTextField;
	private JTextField clientSelectPortTextField;
	private String ip;
	private JTextField clientSelectHostTextField;
	private JComboBox<Integer> maxPlayerCombo;
	private JComboBox<Integer> startMoneyCombo;
	private JComboBox<Integer> startHealthCombo;
	private JComboBox<Integer> startLengthCombo;
	private JSlider gameSpeedSlider;
	private JLabel lblMaximunPlayer;
	private JSlider FieldSizeSlider;

	/** Creates the Main menu of this game. */
	public GameCreatorUI() {
		super("Snake Revolution: Game Configuration");

		this.setPreferredSize(new Dimension(480, 350));

		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(
				Alignment.LEADING).addGroup(
				groupLayout
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE,
								471, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(GroupLayout.DEFAULT_SIZE,
								Short.MAX_VALUE)));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(
				Alignment.LEADING).addGroup(
				groupLayout
						.createSequentialGroup()
						.addGap(9)
						.addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE,
								313, Short.MAX_VALUE).addContainerGap()));

		JPanel panel = new JPanel();
		tabbedPane.addTab("Create Game", null, panel, null);

		lblMaximunPlayer = new JLabel("Maximun Player");
		lblMaximunPlayer.setBounds(12, 18, 99, 16);
		maxPlayerCombo = new JComboBox<Integer>(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8});
		maxPlayerCombo.setBounds(126, 18, 85, 29);
		maxPlayerCombo.setSelectedIndex(1);
		JLabel lblStartingMoney = new JLabel("Starting Money");
		lblStartingMoney.setBounds(17, 46, 94, 16);

		startMoneyCombo = new JComboBox<Integer>(new Integer[] { 0, 100, 500,
				20000 });
		startMoneyCombo.setSelectedIndex(0);
		startMoneyCombo.setBounds(126, 41, 85, 29);

		JLabel lblStartingHealth = new JLabel("Starting Health");
		lblStartingHealth.setBounds(17, 74, 94, 16);

		startHealthCombo = new JComboBox<Integer>(new Integer[] { 15, 60, 100,
				220, 500, 1000 });
		startHealthCombo.setSelectedIndex(1);
		startHealthCombo.setBounds(126, 70, 85, 27);

		startLengthCombo = new JComboBox<Integer>(new Integer[] { 2, 3, 4, 5 });

		startLengthCombo.setSelectedIndex(0);
		startLengthCombo.setBounds(126, 98, 85, 27);

		JLabel lblStartingLength = new JLabel("Starting Length");
		lblStartingLength.setBounds(15, 102, 96, 16);

		gameSpeedSlider = new JSlider(50, 300);
		gameSpeedSlider.setBounds(24, 162, 178, 29);

		JLabel lblDropRate = new JLabel("Game Speed:");
		lblDropRate.setBounds(111, 149, 80, 16);

		JButton launchServerButton = new JButton("Launch Server!!");
		launchServerButton.setBounds(246, 189, 170, 69);
		launchServerButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int port = 7777;
				try {
					port = Integer.parseInt(serverSelectPortTextField.getText());
				} catch (NumberFormatException ex) {
					JOptionPane.showMessageDialog(null, "Invalid Port");
				}

				int player = (Integer) maxPlayerCombo.getSelectedItem();
				int money = (Integer) startMoneyCombo.getSelectedItem();
				int length = (Integer) startLengthCombo.getSelectedItem();
				int health = (Integer) startHealthCombo.getSelectedItem();
				int maxHealth = health;

				int interval = gameSpeedSlider.getValue();
				int size = (int) FieldSizeSlider.getValue();

				GameConfiguration config = new GameConfiguration(player, money,
						length, health, maxHealth, size, size, interval);

				GameServer server = new GameServer(port, config);

				try {
					server.listen();
					server.print("Server start at port: " + port);
				} catch (IOException e1) {
					server.print("Couldn't create the server.");
					server.print("*port: " + port + " May used by another server");
					
				}
			}
		});

		JLabel lblYourIpAddress = new JLabel("Your IP Address: ");
		lblYourIpAddress.setBounds(252, 46, 107, 16);

		showIPTextField = new JTextField();
		showIPTextField.setBounds(246, 68, 178, 28);
		showIPTextField.setColumns(10);
		showIPTextField.setEditable(false);
		ip = "127.0.0.1";
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
			showIPTextField.setText(ip);
		} catch (UnknownHostException e) {
			showIPTextField.setText("Couldn't retrieve your IP Address.");
		}

		JLabel lblPort = new JLabel("Port: ");
		lblPort.setBounds(299, 121, 33, 16);

		serverSelectPortTextField = new JTextField();
		serverSelectPortTextField.setBounds(344, 115, 77, 28);
		serverSelectPortTextField.setText("7777");
		serverSelectPortTextField.setHorizontalAlignment(JTextField.CENTER);
		serverSelectPortTextField.setColumns(10);
		panel.setLayout(null);

		JButton btnCopyToClipboard = new JButton("Copy!");
		btnCopyToClipboard.setBounds(366, 69, 61, 29);
		btnCopyToClipboard.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				StringSelection stringSelection = new StringSelection(ip);
				Clipboard clpbrd = Toolkit.getDefaultToolkit()
						.getSystemClipboard();
				clpbrd.setContents(stringSelection, null);
			}

		});
		panel.add(btnCopyToClipboard);
		panel.add(lblStartingLength);
		panel.add(startLengthCombo);
		panel.add(gameSpeedSlider);
		panel.add(lblDropRate);
		panel.add(lblMaximunPlayer);
		panel.add(maxPlayerCombo);
		panel.add(lblStartingHealth);
		panel.add(lblStartingMoney);
		panel.add(startHealthCombo);
		panel.add(startMoneyCombo);
		panel.add(showIPTextField);
		panel.add(lblYourIpAddress);
		panel.add(launchServerButton);
		panel.add(lblPort);
		panel.add(serverSelectPortTextField);

		JLabel lblFieldSize = new JLabel("Field Size: ");
		lblFieldSize.setBounds(126, 203, 77, 16);
		panel.add(lblFieldSize);

		FieldSizeSlider = new JSlider(20, 60);
		FieldSizeSlider.setBounds(24, 227, 178, 29);
		panel.add(FieldSizeSlider);

		JPanel netBorderPanel = new JPanel();
		netBorderPanel.setBounds(228, 24, 216, 153);
		panel.add(netBorderPanel);

		JPanel panel_1 = new JPanel();
		tabbedPane.addTab("Join Game", null, panel_1, null);

		JLabel lblYourName = new JLabel("Your name: ");

		setNameTextField = new JTextField();
		setNameTextField.setColumns(10);
		try {
			setNameTextField.setText(InetAddress.getLocalHost()
					.getHostAddress());
		} catch (UnknownHostException e) {
			setNameTextField.setText("N/A");
		}

		setNameTextField.setHorizontalAlignment(JTextField.CENTER);

		clientSelectPortTextField = new JTextField();
		clientSelectPortTextField.setColumns(10);
		clientSelectPortTextField.setHorizontalAlignment(JTextField.CENTER);
		clientSelectPortTextField.setText("7777");

		JLabel lblPort_1 = new JLabel("Port: ");

		JButton ReadyButton = new JButton("Ready!");
		ReadyButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				String name;
				try {
					name = InetAddress.getLocalHost().getHostAddress();
				} catch (UnknownHostException e) {
					name = "N/A";
				}
				if (!setNameTextField.getText().isEmpty())
					name = setNameTextField.getText();

				String host = showIPTextField.getText();
				int port = 7777;
				try {
					port = Integer.parseInt(clientSelectPortTextField.getText());
			
				} catch (NumberFormatException ex) {
					JOptionPane.showMessageDialog(null, "Invalid Port");
				}
				if (host.equals(""))
					host = "localhost";
				else
					host = clientSelectHostTextField.getText();

				if (name.length() >= 7)
					name = name.substring(0, 7);
				GameClient client = new GameClient(host, port, name);
				client.start();
			}
		});

		JLabel lblServerIp = new JLabel("Server IP: ");

		clientSelectHostTextField = new JTextField();
		clientSelectHostTextField.setColumns(10);
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1
				.setHorizontalGroup(gl_panel_1
						.createParallelGroup(Alignment.TRAILING)
						.addGroup(
								Alignment.LEADING,
								gl_panel_1
										.createSequentialGroup()
										.addGap(31)
										.addGroup(
												gl_panel_1
														.createParallelGroup(
																Alignment.TRAILING)
														.addGroup(
																gl_panel_1
																		.createSequentialGroup()
																		.addComponent(
																				lblYourName)
																		.addGap(18)
																		.addComponent(
																				setNameTextField,
																				GroupLayout.PREFERRED_SIZE,
																				GroupLayout.DEFAULT_SIZE,
																				GroupLayout.PREFERRED_SIZE))
														.addGroup(
																gl_panel_1
																		.createSequentialGroup()
																		.addGroup(
																				gl_panel_1
																						.createParallelGroup(
																								Alignment.TRAILING)
																						.addGroup(
																								gl_panel_1
																										.createSequentialGroup()
																										.addComponent(
																												lblPort_1)
																										.addGap(18)
																										.addComponent(
																												clientSelectPortTextField,
																												GroupLayout.PREFERRED_SIZE,
																												GroupLayout.DEFAULT_SIZE,
																												GroupLayout.PREFERRED_SIZE))
																						.addGroup(
																								gl_panel_1
																										.createSequentialGroup()
																										.addComponent(
																												lblServerIp)
																										.addGap(18)
																										.addComponent(
																												clientSelectHostTextField,
																												GroupLayout.PREFERRED_SIZE,
																												GroupLayout.DEFAULT_SIZE,
																												GroupLayout.PREFERRED_SIZE)))
																		.addPreferredGap(
																				ComponentPlacement.RELATED)))
										.addGap(38)
										.addComponent(ReadyButton,
												GroupLayout.PREFERRED_SIZE,
												121, GroupLayout.PREFERRED_SIZE)
										.addContainerGap(33, Short.MAX_VALUE)));
		gl_panel_1
				.setVerticalGroup(gl_panel_1
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_panel_1
										.createSequentialGroup()
										.addGroup(
												gl_panel_1
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																gl_panel_1
																		.createSequentialGroup()
																		.addGap(34)
																		.addGroup(
																				gl_panel_1
																						.createParallelGroup(
																								Alignment.BASELINE)
																						.addComponent(
																								setNameTextField,
																								GroupLayout.PREFERRED_SIZE,
																								GroupLayout.DEFAULT_SIZE,
																								GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								lblYourName))
																		.addGap(18)
																		.addGroup(
																				gl_panel_1
																						.createParallelGroup(
																								Alignment.BASELINE)
																						.addComponent(
																								clientSelectHostTextField,
																								GroupLayout.PREFERRED_SIZE,
																								GroupLayout.DEFAULT_SIZE,
																								GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								lblServerIp))
																		.addGap(18)
																		.addGroup(
																				gl_panel_1
																						.createParallelGroup(
																								Alignment.BASELINE)
																						.addComponent(
																								clientSelectPortTextField,
																								GroupLayout.PREFERRED_SIZE,
																								GroupLayout.DEFAULT_SIZE,
																								GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								lblPort_1)))
														.addGroup(
																gl_panel_1
																		.createSequentialGroup()
																		.addGap(96)
																		.addComponent(
																				ReadyButton,
																				GroupLayout.PREFERRED_SIZE,
																				58,
																				GroupLayout.PREFERRED_SIZE)))
										.addContainerGap(113, Short.MAX_VALUE)));
		panel_1.setLayout(gl_panel_1);
		getContentPane().setLayout(groupLayout);
		this.pack();
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	/**
	 * Creates the main menu of this game.
	 * @param args the command line that not be used
	 */
	public static void main(String[] args) {
		new GameCreatorUI();
	}
}
